//
//  RegistrationViewController.m
//  ShareNavigation
//
//  Created by 水木 傅 on 12-5-8.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "RegistrationViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SingletonUser.h"

@implementation RegistrationViewController
{
    NSString *tipLabel;
}

@synthesize RegisterUserText;
@synthesize RegisterPassWordText;
@synthesize ReEnterPassWordText;
@synthesize RegisterButton;
@synthesize ErrorUserIDLabel;

//---  接收到请求发回来的消息的函数  ---
//－－－  注册请求  －－－
- (void)requestRegisterFinished:(ASIHTTPRequest *)request
{
    NSString *ResponseString = [request responseString];
    NSLog(@"%@",ResponseString);
    if([ResponseString isEqualToString:@"TRUE"])
    {
        UIAlertView *alert;
        ResponseString = @"注册成功";
        alert = [[UIAlertView alloc]
                 initWithTitle:@""
                 message:ResponseString
                 delegate:self
                 cancelButtonTitle:@"返回"
                 otherButtonTitles:nil];
        alert.tag = 1;
        [alert show];
    }
    else
    {
        UIAlertView *alert;
        alert = [[UIAlertView alloc]
                 initWithTitle:@"警告"
                 message:ResponseString
                 delegate:self
                 cancelButtonTitle:@"返回"
                 otherButtonTitles:@"重新注册",nil];
        [alert setTag:2];
        [alert show];
    }
}

- (void)requestRegisterFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",[error localizedFailureReason]);
}
//－－－  验证用户名请求  －－－
- (void)requestVerFinished:(ASIHTTPRequest *)request
{
    NSString *ResponseString = [request responseString];
    NSLog(@"%@",ResponseString);
    if([ResponseString isEqualToString:@"TRUE"])
    {
        ErrorUserIDLabel.textColor = [UIColor blueColor];
        ErrorUserIDLabel.text = @"该用户名可用";
        ErrorUserIDLabel.hidden = FALSE;
    }
    else
    {
        ErrorUserIDLabel.textColor = [UIColor redColor];
        ErrorUserIDLabel.text = @"该用户名已经被注册";
        ErrorUserIDLabel.hidden = FALSE;
        RegisterButton.enabled = FALSE;
    }
}

- (void)requestVerFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",[error localizedFailureReason]);
}


//---  发送注册消息  ---
-(void) SendRegister
{
    self.navigationItem.title = @"注册中...";
    //---  注册消息发送  ---
    NSURL *url = [NSURL URLWithString:@"http://localhost/~walker/ShareNavigationSVN/trunk/ShareNavigationPHP/Verification.php"];
    ASIFormDataRequest *request=[[ASIFormDataRequest alloc] initWithURL:url];
    [request setRequestMethod:@"POST"];
    [request setPostValue:RegisterUserText.text forKey:@"UserID"];
    [request setPostValue:RegisterPassWordText.text forKey:@"PassWord"];
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestRegisterFinished:)];
    [request setDidFailSelector:@selector(requestRegisterFailed:)];
    [request setDefaultResponseEncoding:NSUTF8StringEncoding];
    //---  发送请求信息  ----
    [request startAsynchronous];
}


//---  验证用户名是否有效  ---
-(BOOL) VerUserId :(NSString *)VerUserID
{
    if([VerUserID isEqualToString:@""])
        return FALSE;
    //---  正则表达式,过滤字母，数字，汉字  ---
    NSString *regex = @"^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$";
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:VerUserID];
}

//---  验证密码是否一样  ---
-(BOOL) VerPassWord
{
    if([RegisterPassWordText.text isEqualToString:ReEnterPassWordText.text]
       &&  ![ReEnterPassWordText.text isEqualToString:@""])
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

//---  控件的响应事件  ---

//---  用户名输入完成响应事件  ---
- (IBAction)DidEnd:(id)sender {
    NSString *UserIDString = RegisterUserText.text;
    if ([self VerUserId:UserIDString] == NO) {
        self.RegisterUserText.textColor = [UIColor redColor];
        ErrorUserIDLabel.text = @"用户名中含有非法字符";
        ErrorUserIDLabel.hidden = FALSE;
    }
    else
    {
        self.RegisterUserText.textColor = [UIColor blackColor];
        ErrorUserIDLabel.hidden = TRUE;
        //---  发送用户名唯一性的验证  ----
        NSURL *url = [NSURL URLWithString:@"http://localhost/~walker/ShareNavigationSVN/trunk/ShareNavigationPHP/Verification.php"];
        ASIFormDataRequest *request=[[ASIFormDataRequest alloc] initWithURL:url];
        [request setRequestMethod:@"POST"];
        [request setPostValue:RegisterUserText.text forKey:@"UserID"];
        [request setPostValue:@"TRUE" forKey:@"VerificationUserID"];
        [request setDidFinishSelector:@selector(requestVerFinished:)];
        [request setDidFailSelector:@selector(requestVerFailed:)];
        [request setDelegate:self];
        [request setDefaultResponseEncoding:NSUTF8StringEncoding];
        [request startAsynchronous];
    }
}

- (IBAction)RegisterUserId:(id)sender {
    [RegisterPassWordText becomeFirstResponder];

}

//---  输入密码  ---
- (IBAction)RegisterPassWord:(id)sender {
    [ReEnterPassWordText becomeFirstResponder];
}
//---  再一次输入密码  ---
- (IBAction)ReEnterPassWord:(id)sender {
    if([self VerPassWord])
    {
        //[self SendRegister];
        [ReEnterPassWordText resignFirstResponder];
    }
    else
    {
        NSString *msg = @"两次输入的密码不同或尚未输入密码，请重新输入。";
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"警告"
                              message:msg
                              delegate:self
                              cancelButtonTitle:@"返回"
                              otherButtonTitles:nil];
        [alert setTag:0];
        [alert show];
    }
}
//---  当输入变化时，验证是否正确输入  ---
- (IBAction)InputChange:(id)sender {
    if([self VerUserId:RegisterUserText.text] && [self VerPassWord])
    {
       // NSLog(@"true");
        [RegisterButton setEnabled:TRUE];
    }
    else
    {
       // NSLog(@"false");
        [RegisterButton setEnabled:FALSE];
    }
}

- (IBAction)RegistionButtonPress:(id)sender {
    [self SendRegister];
}


- (void)viewDidUnload {
    [self setRegisterUserText:nil];
    [self setRegisterPassWordText:nil];
    [self setReEnterPassWordText:nil];
    [self setRegisterButton:nil];
    [self setErrorUserIDLabel:nil];
    [super viewDidUnload];
}

#pragma ---  重写tableview 的函数  ---
//---  重写函数，tableview中的行不可被选中  ---
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:
            [RegisterUserText becomeFirstResponder];
            break;
        case 1:
            [RegisterPassWordText becomeFirstResponder];
            break;
        case 2:
            [ReEnterPassWordText becomeFirstResponder];
            break;
        default:
            break;
    }
    return nil;
}

#pragma ---  实现delegate中的方法  ----

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView.tag == 0)
    {
        //---  光标重新聚焦到第二行的密码输入框  ---
        [ReEnterPassWordText becomeFirstResponder];
    }
    else if(alertView.tag == 1)
    {
        [SingletonUser shareManager].HasLogin = TRUE;
        [SingletonUser shareManager].UserID = self.RegisterUserText.text;
        [SingletonUser shareManager].PassWord = self.RegisterPassWordText.text;
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        if(buttonIndex == 0)
        {
             [self dismissViewControllerAnimated:YES completion:nil];
        }
        else
        {
            [RegisterUserText becomeFirstResponder];
        }

    }
}
@end
